package com.qinggeng.project.api.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qinggeng.common.constant.Constants;
import com.qinggeng.common.enums.ShowTypeEnum;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.framework.redis.RedisLock;
import com.qinggeng.framework.web.controller.BaseController;
import com.qinggeng.framework.web.domain.AjaxResult;
import com.qinggeng.project.api.dto.OrdersDistDto;
import com.qinggeng.project.api.security.annotation.LoginRequired;
import com.qinggeng.project.api.security.utils.ApiUtils;
import com.qinggeng.project.api.service.IApiMemberService;
import com.qinggeng.project.system.domain.*;
import com.qinggeng.project.system.service.*;
import com.qinggeng.project.tool.pay.domain.AliWithdrawModal;
import com.qinggeng.project.tool.pay.service.AliPayService;
import com.qinggeng.project.tool.pay.utils.PayUtils;
import com.qinggeng.project.tool.sms.service.ISysSmsService;
import com.qinggeng.project.tool.third.domain.SysThirdPlatform;
import com.qinggeng.project.tool.third.service.ISysThirdPlatformService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Api(tags = "配送员模块")
@RestController
@RequestMapping("${apiPath}/dist")
public class ApiDistController extends BaseController {

    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IDistributionPointService pointService;
    @Autowired
    private IApiMemberService memberService;
    @Autowired
    private ISysSmsService smsService;
    @Autowired
    private IUserAliasService userAliasService;

    @Autowired
    private IGoodsStatisticsService goodsStatisticsService;

    @Autowired
    private IOrderStatisticsService orderStatisticsService;

    @Autowired
    private IUserWalletService userWalletService;

    @Autowired
    private ISysThirdPlatformService sysThirdPlatformService;

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private UserBindService userBindService;

    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation("我的订单列表")
    @GetMapping("/discOrdersList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name="startTime",value = "开始时间的时间戳",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name="endTime",value = "结束时间的时间戳",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true)
    })
    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_COURIER)
    public AjaxResult discOrdersList(Long startTime,Long endTime) {
        if(startTime!=null&&endTime!=null&&startTime>endTime){
            return AjaxResult.error("开始时间不能晚于结束时间", ShowTypeEnum.用户.getValue());
        }
        Map<String,Object> data = Maps.newHashMap();
        //筛选时间为空，则默认查询当天订单（2=当天，3=根据时间筛选）
        Integer status=(startTime!=null&&endTime!=null)?3:2;
        //根据骑手ID查询配送点
        DistributionPoint point = pointService.selectPointByCourierId(ApiUtils.getUserId());
        startPage();
        List<OrdersDistDto> ordersDistDtoList = ordersService.selectOrdersDiscDtoUserList(status,point.getId(),startTime,endTime);
        //今日完成数量
        data.put("dayNum",ordersService.selectOrdersDiscDtoCount(point.getId(),2,null,null));
        //累计完成数量
        data.put("totalNum",ordersService.selectOrdersDiscDtoCount(point.getId(),status,startTime,endTime));
        data.put("list",ordersDistDtoList);
        return AjaxResult.success(data);
    }

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_COURIER)
    @ApiOperation("验证码")
    @PostMapping("/code")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "event",value = "0=发送  1=验证",dataType = "Integer",paramType = "query",required = false),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", paramType = "query"),
    })
    public AjaxResult verifyCode(
            @RequestParam(name = "event",defaultValue = "0") Integer event, String code) {
        SysUser sysUser = ApiUtils.getApiUser().getUser();
        //发送短信验证码
        if(event==0){
            try{
                smsService.snedSmsVerifyCode(sysUser.getPhonenumber());
            }catch(Exception e){
                e.printStackTrace();
                return AjaxResult.error(e.getMessage());
            }
        }
        //验证短信验证码
        if(event==1){
            String checkCode = smsService.getCode(sysUser.getPhonenumber(), "verify");
            if (StringUtils.isEmpty(checkCode) || !code.equals(checkCode)) {
                return AjaxResult.error("验证码错误",ShowTypeEnum.用户.getValue());
            }
        }
        return AjaxResult.success();
    }


    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_COURIER)
    @ApiOperation("设置密码")
    @PostMapping("/bindPwd")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", paramType = "query"),
    })
    public AjaxResult bindPwd(String password) {
        SysUser sysUser = ApiUtils.getApiUser().getUser();
        if (StringUtils.isEmpty(password)) {
            return AjaxResult.error("请输入密码",ShowTypeEnum.用户.getValue());
        }
        int rows=memberService.updatePassWord(sysUser.getPhonenumber(), password, sysUser.getUserType());
        //清除token令牌
        if(rows>0){
            UserAlias where=new UserAlias();
            where.setUserId(sysUser.getUserId());
            where.setUserType(sysUser.getUserType());
            List<UserAlias> userAliasList=userAliasService.selectUserAliasList(where);
            for (UserAlias alias:userAliasList
                 ) {
                ApiUtils.outLogin(alias.getToken());
            }
        }
        return toAjax(rows);
    }

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_COURIER)
    @ApiOperation("商品销量统计")
    @GetMapping("/goodsStatistics")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "shopId",value = "商铺ID",dataType = "Long",paramType = "query",required = true),
            @ApiImplicitParam(name = "index",value = "查询索引（10=单商品统计，20=分类商品统计）",defaultValue = "10",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "startTime",value = "开始查询时间",dataType = "Long",paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束查询时间", dataType = "Long", paramType = "query"),
    })
    public AjaxResult goodsStatisticsList(Long shopId, Long classifyId,@RequestParam(defaultValue = "10") Integer index, Long startTime, Long endTime)    {
        DistributionPoint point=pointService.selectPointByCourierId(ApiUtils.getUserId());
        if(point==null){
            return AjaxResult.error("配送点不存在",ShowTypeEnum.用户.getValue());
        }
        Map<String,Object> data= Maps.newHashMap();
        OrderStatistics orderStatistics=orderStatisticsService.selectPointOrderStatisticsByPointId(point.getId(),startTime,endTime);
        data.put("orderNum",orderStatistics.getOrderNum());
        data.put("orderAllMoney",orderStatistics.getOrderAllMoeny());
        List<GoodsStatistics> list= Lists.newArrayList() ;
        //单商品销量统计
        if(index==10){
            startPage();
            list=goodsStatisticsService.selectGoodsStatisticsList(shopId,point.getId(),classifyId,startTime,endTime);
        }
        //分类商品销量统计
        if(index==20){
            startPage();
            list=goodsStatisticsService.selectGoodsStatisticsListByClassifyId(shopId,point.getId(),startTime,endTime);
        }
        data.put("list",list);
        return AjaxResult.success(data);
    }

    @LoginRequired(role = ApiUtils.DEFAULT_ROLE_COURIER)
    @ApiOperation("用户提现")
    @GetMapping("/withdrawMoney")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", dataType = "String", name = Constants.TOKEN, value = "token标记", required = true),
            @ApiImplicitParam(name = "price",value = "提现金额",dataType = "BigDecimal",paramType = "query",required = true),
            @ApiImplicitParam(name = "platform",value = "平台 wx,alipay",dataType = "String",paramType = "query"),
    })
    public AjaxResult withdrawMoney(BigDecimal price,String platform){
        RedisLock redisLock = new RedisLock(redisTemplate,"USER_ID"+ApiUtils.getUserId());
        if(true){
            return AjaxResult.error("当前app不在维护,请使用品味生活",ShowTypeEnum.用户.getValue());
        }
        try {
            if (price.compareTo(new BigDecimal("0.1"))<0){
                return AjaxResult.error("金额不能小于0.1",ShowTypeEnum.用户.getValue());
            }
            if (price.compareTo(new BigDecimal("0"))<=0){
                return AjaxResult.error("金额不存在,price="+price,ShowTypeEnum.用户.getValue());
            }
            //获取用户钱包数据
            UserWallet userWallet = userWalletService.selectUserWalletByUserId(ApiUtils.getUserId());
            if (userWallet == null){
                return AjaxResult.error("用户钱包不存在",ShowTypeEnum.用户.getValue());
            }
            //比较可用金额与提取金额大小
            int result = price.compareTo(userWallet.getTotalPrice());
            if (result > 0){
                return AjaxResult.error("金额超出,请重试,price="+price,ShowTypeEnum.用户.getValue());
            }

            //根据平台类型调用提现方式
            if (platform.equals("wx")){
                return AjaxResult.error("当前提现功能未开放:"+platform,ShowTypeEnum.用户.getValue());
//                platform = "wxByGgzy";
//                SysThirdPlatform sysThirdPlatform = sysThirdPlatformService.selectSysThirdPlatformByCode(platform);
            }else if (platform.equals("alipay")){
                //查询支付宝绑定对象信息
                UserBind userBind = userBindService.selectUserBindByUserIdAndPlatform(ApiUtils.getUserId(), platform);
                platform = "alipayByGgzy";
                //根据平台名称查询平台信息
                SysThirdPlatform sysThirdPlatform = sysThirdPlatformService.selectSysThirdPlatformByCode(platform);
                //解析公钥私钥
                JSONObject alipayConfig = JSON.parseObject(sysThirdPlatform.getOtherParams());
                //封装退款模型
                AliWithdrawModal modal = new AliWithdrawModal();
                modal.setAppid(sysThirdPlatform.getAppId());
                modal.setPubliceKey(alipayConfig.getString("publiceKey"));
                modal.setPrivateKey(alipayConfig.getString("privateKey"));
                modal.setAliAccount(userBind.getUniqueId());
                modal.setMoney(price+"");
                modal.setOrderId(PayUtils.getOrderCode());
                modal.setRemark("提现");
                modal.setPayerShowName("果果专员");
                modal.setPayeeRealName(userBind.getRealUserName());
                //执行退款逻辑
                boolean flag = aliPayService.tixian(modal,userWallet);
                if (flag){
                    return AjaxResult.success("提现成功",ShowTypeEnum.用户.getValue());
                }else {
                    return AjaxResult.error("提现失败",ShowTypeEnum.用户.getValue());
                }
            }
        }catch (NumberFormatException e){
            e.printStackTrace();
            return AjaxResult.error("请输入正确金额",ShowTypeEnum.用户.getValue());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统异常" + e.getMessage(),ShowTypeEnum.用户.getValue());
        }finally {
            redisLock.unlock();
        }
        return AjaxResult.error("提现失败",ShowTypeEnum.用户.getValue());
    }


}
